package com.heima.behavior.service.Impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApCollectionBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.CollectionBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApCollection;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApCollectionBehaviorServiceimpl implements ApCollectionBehaviorService {
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    MongoTemplate mongoTemplate;
    @Override
    public ResponseResult collectBehavior(CollectionBehaviorDTO dto) {
        //1。检查参数
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);//1 需要登录后操作
        }
        //2.查询实体行为
        ApBehaviorEntry behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (behaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "没能获取实体行为");
        }

    Query query = Query.query(Criteria.where("entryId")
                .is(behaviorEntry.getId())
                .and("articleId").is(dto.getArticleId()));
        //3。查询收藏行为是否已存在
      if (dto.getOperation().intValue()==0){
          ApCollection apCollection= mongoTemplate.findOne(query, ApCollection.class);
          if (apCollection!=null){
CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"你已收藏该文章");
          }
          //4。添加收藏行为
          apCollection=new ApCollection();
          apCollection.setEntryId(behaviorEntry.getId());
          apCollection.setArticleId(dto.getArticleId());
          apCollection.setCollectionTime(new Date());

          apCollection.setType((short)0);
          mongoTemplate.save(apCollection);

      }else{
          //5。取消收藏行为
          mongoTemplate.remove(query,ApCollection.class);
      }
        return ResponseResult.okResult();
    }
}
